"""
聊天API接口
"""
from typing import Optional, Dict, Any
from fastapi import APIRouter, Depends, HTTPException, status, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from sqlalchemy.orm import Session

from app.models.base import get_db
from app.models.session import MessageType
from app.services.ai_service import AIService
from app.services.session_service import SessionService

router = APIRouter(prefix="/api/chat", tags=["chat"])

# 请求模型
class ChatRequest(BaseModel):
    message: str
    session_id: Optional[str] = None
    system_context: Optional[Dict[str, Any]] = None

class ChatResponse(BaseModel):
    response: str
    session_id: str
    confidence_score: float
    has_safety_warning: bool
    safety_info: Optional[Dict] = None

# 延迟初始化服务
ai_service = None
session_service = SessionService()

def get_ai_service():
    """获取AI服务实例（延迟初始化）"""
    global ai_service
    if ai_service is None:
        ai_service = AIService()
    return ai_service


@router.post("/send", response_model=ChatResponse)
async def send_message(
    request: ChatRequest,
    db: Session = Depends(get_db)
):
    """发送聊天消息"""
    try:
        # 创建或获取会话
        if request.session_id:
            chat_session = session_service.get_session(db, request.session_id)
            if not chat_session:
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="会话不存在"
                )
        else:
            chat_session = session_service.create_session(
                db, 
                system_context=request.system_context
            )
        
        # 保存用户消息
        session_service.add_message(
            db,
            chat_session.session_id,
            MessageType.USER,
            request.message
        )
        
        # 生成AI回复
        ai_response, confidence_score, operation_id = await get_ai_service().generate_response(
            db,
            chat_session.session_id,
            request.message,
            request.system_context
        )
        
        # 保存AI回复
        session_service.add_message(
            db,
            chat_session.session_id,
            MessageType.ASSISTANT,
            ai_response,
            confidence_score=confidence_score,
            operation_id=operation_id
        )

        return ChatResponse(
            response=ai_response,
            session_id=chat_session.session_id,
            confidence_score=confidence_score,
            has_safety_warning=False,
            safety_info=None
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"处理消息失败: {str(e)}"
        )


@router.get("/session/{session_id}/messages")
async def get_session_messages(
    session_id: str,
    limit: Optional[int] = 50,
    db: Session = Depends(get_db)
):
    """获取会话消息历史"""
    try:
        messages = session_service.get_session_messages(db, session_id, limit)
        
        return {
            "session_id": session_id,
            "messages": [
                {
                    "id": msg.id,
                    "type": msg.message_type.value,
                    "content": msg.content,
                    "timestamp": msg.created_at.isoformat(),
                    "confidence_score": msg.confidence_score
                }
                for msg in messages
            ]
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取消息历史失败: {str(e)}"
        )


@router.get("/session/{session_id}/summary")
async def get_session_summary(
    session_id: str,
    db: Session = Depends(get_db)
):
    """获取会话摘要"""
    try:
        summary = await get_ai_service().summarize_conversation(db, session_id)
        statistics = session_service.get_session_statistics(db, session_id)
        
        return {
            "session_id": session_id,
            "summary": summary,
            "statistics": statistics
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"生成摘要失败: {str(e)}"
        )


class NewSessionRequest(BaseModel):
    system_context: Optional[Dict[str, Any]] = None

@router.options("/session/new")
async def options_session_new():
    """处理OPTIONS预检请求"""
    return JSONResponse(
        content={},
        headers={
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
            "Access-Control-Allow-Credentials": "true"
        }
    )

@router.post("/session/new")
async def create_new_session_post(
    request: NewSessionRequest,
    db: Session = Depends(get_db)
):
    """创建新会话 (POST)"""
    try:
        chat_session = session_service.create_session(db, system_context=request.system_context)

        return {
            "session_id": chat_session.session_id,
            "created_at": chat_session.created_at.isoformat()
        }

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建会话失败: {str(e)}"
        )

@router.get("/session/new")
async def create_new_session_get(
    db: Session = Depends(get_db)
):
    """创建新会话 (GET)"""
    try:
        chat_session = session_service.create_session(db, system_context=None)

        return {
            "session_id": chat_session.session_id,
            "created_at": chat_session.created_at.isoformat()
        }

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建会话失败: {str(e)}"
        )


@router.delete("/session/{session_id}")
async def delete_session(
    session_id: str,
    db: Session = Depends(get_db)
):
    """删除会话"""
    try:
        success = session_service.delete_session(db, session_id)
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="会话不存在"
            )
        
        return {"message": "会话已删除"}
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除会话失败: {str(e)}"
        )


@router.get("/sessions")
async def list_sessions(
    limit: int = 20,
    keyword: Optional[str] = None,
    db: Session = Depends(get_db)
):
    """获取会话列表"""
    try:
        sessions = session_service.search_sessions(
            db, 
            keyword=keyword, 
            limit=limit
        )
        
        return {
            "sessions": [
                {
                    "session_id": session.session_id,
                    "title": session.title,
                    "status": session.is_active,
                    "created_at": session.created_at.isoformat(),
                    "updated_at": session.updated_at.isoformat()
                }
                for session in sessions
            ]
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取会话列表失败: {str(e)}"
        )
